package com.example.templateapp.ui.web

import android.os.Bundle
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.templateapp.R
import com.example.templateapp.databinding.ActivityWebViewBinding


class WebViewActivity : AppCompatActivity() {

    private lateinit var binding: ActivityWebViewBinding

    companion object {
        const val TITLE_KEY = "TITLE_KEY"
        const val URL_KEY = "URL_KEY"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_web_view)
        binding.title.setLeftClickListener { finish() }

        initWeb()

        with(intent) {
            val title = getStringExtra(TITLE_KEY) ?: null
            if (title != null) {
                binding.title.setTitle(title)
            }

            val url = getStringExtra(URL_KEY) ?: null
            if (url != null) {
                binding.web.loadUrl(url)
            }

        }

        val data =
            " <p><a href=\\\"https://www.diaochapai.com/survey3054261\\\" target=\\\"_blank\\\">保卫科货车司机测评链接（点我测评）</a><br></p>"

        binding.web.loadData(data, "text/html; charset=UTF-8", null)
    }

    private fun initWeb() {

        binding.web.settings.javaScriptEnabled = true
        binding.web.settings.domStorageEnabled = true
        binding.web.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                view?.loadUrl(request?.url.toString())
                return true
            }
        }
        binding.web.webChromeClient = object : WebChromeClient() {
        }
    }
}